package com.binhthuan.catechist.server.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.binhthuan.catechist.server.ErrorObject;
import com.binhthuan.catechist.server.ResponseObject;
import com.binhthuan.catechist.server.bus.StatusBUS;
import com.binhthuan.catechist.server.domain.Status;
import com.binhthuan.catechist.shared.constant.Parameter;

public class StatusServlet extends AbstractServlet {

    /**
     * 
     */
    private static final long serialVersionUID = -6065753716727210553L;

    @Override
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        addStatus(request, response);
    }

    @Override
    protected void fetch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(request.getParameter(Parameter.ID) == null) {
            getAllStatuses(request, response);
        } else {
            getStatus(request, response);
        }
    }

    @Override
    protected void remove(HttpServletRequest request, HttpServletResponse response, boolean confirmation) throws ServletException,
            IOException {
        deleteStatus(request, response);
    }

    @Override
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        updateStatus(request, response);
    }

    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void getAllStatuses(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter(Parameter.STATUS_TYPE);

        try {
            int statusType = Integer.parseInt(type);

            StatusBUS bus = new StatusBUS();
            List<Status> statuses = bus.getAllStatuses(statusType);

            sendResponse(new ResponseObject(statuses).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * @param request
     * @param response
     * @throws IOException
     */
    private void getStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter(Parameter.STATUS_TYPE);
        String id = request.getParameter(Parameter.ID);

        try {
            int statusType = Integer.parseInt(type);
            int statusId = Integer.parseInt(id);

            StatusBUS bus = new StatusBUS();
            Status status = bus.getStatusById(statusType, statusId);

            sendResponse(new ResponseObject(status).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void addStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter(Parameter.STATUS_TYPE);
        String name = request.getParameter(Parameter.NAME);

        try {
            int statusType = Integer.parseInt(type);

            Status obj = new Status();
            obj.setName(name);
            
            StatusBUS bus = new StatusBUS();
            if (bus.getStatusByName(statusType, name.trim()) != null) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().duplicatedName());
                sendResponse(error.toJson());
                return;
            }
            if (bus.save(statusType, obj)) {
                sendResponse(new ResponseObject(obj).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void deleteStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String areaId = request.getParameter(Parameter.ID);
        String type = request.getParameter(Parameter.STATUS_TYPE);
        
        try {
            int id = Integer.parseInt(areaId);
            int statusType = Integer.parseInt(type);

            StatusBUS bus = new StatusBUS();
            
            if (bus.isInUsed(statusType, id)) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().itemIsInUsed("\"" + ((Status)bus.getStatusById(statusType, id)).getName() + "\""));
                sendResponse(error.toJson());
                return;
             }

            if (bus.delete(statusType, id)) {
                sendResponse(new ResponseObject((Object) null).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void updateStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter(Parameter.STATUS_TYPE);
        String id = request.getParameter(Parameter.ID);
        String name = request.getParameter(Parameter.NAME);

        try {
            int statusId = Integer.parseInt(id);
            int statusType = Integer.parseInt(type);

            StatusBUS bus = new StatusBUS();
            Status obj = bus.getStatusByName(statusType, name.trim());
            if (obj != null && obj.getId() != statusId) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().duplicatedName());
                sendResponse(error.toJson());
                return;
            }

            obj = bus.getStatusById(statusType, statusId);
            obj.setName(name);

            if (bus.save(statusType, obj)) {
                sendResponse(new ResponseObject(obj).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}
